import os
import time
import yaml

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

APK_TOOL = 'JAVA -jar ' + os.getcwd() + '\\apktool.jar'

SING_PATH = 'Java -jar ' + os.getcwd() + '\\signapk.jar  ' + os.getcwd() + '\\platform.x509.pem  ' + os.getcwd() + '\\platform.pk8  '


def change_android_manifest(folder, package):
    tree = ET.parse(folder + '\\AndroidManifest.xml')
    root = tree.getroot()
    # package = root.attrib["package"]
    root.set('package', package)
    tree.write(folder + '\\AndroidManifest.xml')


def change_version_code(folder, code, versionName):
    f = open(folder + '\\apktool.yml', 'r+')
    dataMap = yaml.load(f)
    dataMap['versionInfo']['versionCode'] = code
    dataMap['versionInfo']['versionName'] = versionName
    f = open(folder + '\\apktool.yml', 'w+')
    yaml.dump(dataMap, f)
    f.close()


def execCmd(cmd):
    r = os.popen(cmd)
    str = r.read()
    r.close()
    return str


def GetApkPath(path, name, code, version_name):
    exist = os.path.exists(path)
    if not exist:
        print(path, '文件不存在')
        return
    if not os.path.splitext(path)[1] == '.apk':
        print(path, '文件不是APK')
        return
    unzip_cmd = APK_TOOL + '  d  ' + path + ' -f'
    print(unzip_cmd)
    cmd_text = execCmd(unzip_cmd)
    if 'already exists' in cmd_text:
        print('文件已经存在请先删除')
        return
    if 'Copying original files...' not in cmd_text:
        print('解包失败')
        return
    apk_name = path.split('\\')[-1]
    folder = apk_name.replace('.apk', '')
    apk_folder = os.getcwd() + '\\' + folder
    print('解包存放路径：', apk_folder)
    print('解包成功开始替换包名')
    change_android_manifest(apk_folder, name)
    print('替换包名为:', name)
    change_version_code(apk_folder, code, version_name)
    print('改变VersionCode为:', code)
    print('改变VersionName为:', version_name)
    print('开始合包')

    zipped_cmd = APK_TOOL + '  b  ' + apk_folder
    print(zipped_cmd)
    zipped_cmd_text = execCmd(zipped_cmd)
    if ' Copying unknown files/dir...' not in zipped_cmd_text:
        print('合包失败')
        return
    print('合包成功开始签名')
    sing_cmd = SING_PATH + apk_folder + '\\dist\\' + apk_name + '  sing_' + apk_name
    print(sing_cmd)
    sing_cmd_text = execCmd(sing_cmd)
    if sing_cmd_text != '':
        print('签名失败')
        return
    print('签名成功')
    time.sleep(5)
    print('操作完成')


if __name__ == '__main__':
    input_path = input('请输入APK地址:')
    input_name = input('请输入包名:')
    input_version_name = input('请输入版本Name:')
    input_code = input('请输入版本Code:')
    GetApkPath(input_path, input_name, input_code, input_version_name)
